package com.ruoyi.file.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;

import org.springframework.context.annotation.Primary;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;


import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;



@Primary
@Service
public class AliOssSysFileServiceImpl {

    private static final String endpoint = "https://oss-cn-beijing.aliyuncs.com";
    private static final String accessKeyId = "LTAI5tSQP9m3cHTTJna1JGLD";
    private static final String accessKeySecret = "xmMEt2DWcDVa5N4nZXwsAvCBG49UCm";
    private static final String bucketName = "jas-file";


    public void deleteOssFile(String fileName) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.deleteObject(bucketName, fileName);
        ossClient.shutdown();
    }

    /**
     * 上传文件
     */
    public String uploadFile(MultipartFile file) throws IOException {
        // 获取上传文件的输入流
        InputStream inputStream = file.getInputStream();
        // 重命名文件,避免文件覆盖
        String fileName = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + "-" + file.getOriginalFilename();
        return upload(inputStream, fileName);
    }

    public String upload(InputStream inputStream, String fileName) {
        // 上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, fileName, inputStream);
        // 访问路径: https://[bucketName].[endpointHost]/fileName
        // 例如: https://zifeiyu01-oss.oss-cn-fuzhou.aliyuncs.com/20240220120000-1.jpg
        String url = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + fileName;
        ossClient.shutdown();
        return url;
    }
}
